<template>
  <view class="container">
    <!-- 店铺头部 -->
    <view class="shop-header">
      <image 
        :src="shopData.businessLicenseImage || '/static/default-shop.jpg'" 
        class="shop-banner"
        mode="aspectFill"
      />
      <text class="shop-name">{{ shopData.storeName || '未命名店铺' }}</text>
    </view>

    <!-- 店铺信息 -->
    <view class="info-card">
      <view class="info-line">
        <text class="rating">{{ (shopData.averageRating || 0).toFixed(1) }}分</text>
        <text class="sales">销量：{{ shopData.orderCount || 0 }}</text>
        <text class="distance">距离1.2km</text>
      </view>
      <text class="hours">营业时间：{{ shopData.businessHours || '暂未提供营业时间' }}</text>
    <!-- 
	 <text class="address">坐标：{{ shopData.longitude || '' }}, {{ shopData.latitude || '' }}</text>
    -->
	</view>

    <!-- 服务项目 -->
    <view class="service-card">
      <text class="section-title">服务项目（{{ serviceItems.length }}）</text>
      <view class="service-list">
        <view 
          v-for="item in serviceItems" 
          :key="item.serviceId" 
          class="service-item"
        >
          <view class="service-info">
            <text class="service-name">{{ item.serviceName }}</text>
            <text class="service-desc">{{ item.serviceDesc || '暂无详细描述' }}</text>
          </view>
          <view class="price-section">
            <text class="current-price">￥{{ item.currentPrice?.toFixed(2) }}</text>
            <text 
              class="original-price"
              v-if="item.currentPrice < item.originalPrice"
            >
              ￥{{ item.originalPrice?.toFixed(2) }}
            </text>
          </view>
          <button 
            class="service-order-btn"
            @click="navigateToOrderConfirm(item.serviceId)"
          >立即预约</button>
        </view>
      </view>
      <view v-if="serviceItems.length === 0" class="empty-tip">
        <text>该店铺暂无服务项目</text>
      </view>
    </view>

 <!-- 修改后的用户评价模板 -->
 <view class="comment-card">
   <text class="section-title">服务评价（{{ reviews.length }}）</text>
   <view 
     v-for="(review, index) in reviews" 
     :key="review.reviewId"
     class="comment-item"
   >
     <view class="user-header">
       <text class="username">用户{{ review.memberId.toString().slice(-4) }}</text>
       <text class="rating-stars">★{{ review.rating.toFixed(1) }}</text>
     </view>
     <text class="comment-time">{{ formatDate(review.reviewTime) }}</text>
     <text class="comment-content">{{ review.content }}</text>
     <scroll-view 
       v-if="review.images && review.images.length > 0" 
       class="image-grid" 
       scroll-x
     >
       <image 
         v-for="(img, imgIndex) in review.images" 
         :key="imgIndex"
         :src="img"
         mode="aspectFill"
         class="comment-image"
       />
     </scroll-view>
   </view>
   <view v-if="reviews.length === 0" class="empty-comment">
     <text>暂无评价，快来留下第一条评论吧~</text>
   </view>
 </view>

    <!-- 底部操作栏 -->
    <view class="footer-bar">
      <button class="contact-btn" @click="openPhoneDialog('400-123-4567')">联系客服</button>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-mask">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 电话弹窗 -->
    <uni-popup ref="phonePopup" type="center">
      <view class="phone-dialog">
        <text class="phone-title">客服电话</text>
        <text class="phone-number">{{ currentPhone }}</text>
        <view class="dialog-buttons">
          <button class="call-btn" @click="makePhoneCall">立即拨打</button>
          <button class="cancel-btn" @click="closePhoneDialog">取消</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 店铺数据
const shopData = ref({
  averageRating: 0,
  orderCount: 0,
  storeName: '加载中...'
});

// 服务项目数据
const serviceItems = ref([]);
const loading = ref(true);
const currentPhone = ref('');
const phonePopup = ref(null);
const reviews = ref([]);
// 生命周期钩子
onLoad(async (options) => {
  try {
    if (!options?.id) {
      handleError('缺少店铺ID');
      return;
    }

    const storeId = options.id;
	console.log("获取到的id:"+storeId);
    await Promise.all([
      fetchStoreInfo(storeId),
      fetchServiceItems(storeId),
	  fetchReviews(storeId)
    ]);
  } catch (error) {
    console.error('页面加载失败:', error);
    handleError('数据加载失败，请重试');
  } finally {
    loading.value = false;
  }
});

// 获取店铺信息
const fetchStoreInfo = (storeId) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `http://localhost:10001/store/info?storeId=${storeId}`,
      success: (res) => {
        if (res.statusCode === 200 && res.data?.length > 0) {
          shopData.value = {
            ...res.data[0],
            averageRating: Number(res.data[0].averageRating) || 0,
            orderCount: Number(res.data[0].orderCount) || 0
          };
          uni.setNavigationBarTitle({ title: shopData.value.storeName });
          resolve();
        } else {
          reject(new Error('店铺信息获取失败'));
        }
      },
      fail: reject
    });
  });
};

// 获取服务项目
const fetchServiceItems = (storeId) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `http://localhost:10001/serviceItem/getByStoreId?storeId=${storeId}`, // 修正参数名
      success: (res) => {
        // console.log('服务项目接口响应:', res);
        if (res.statusCode === 200) {
          // 根据实际返回数据结构调整
          const items = res.data?.serviceItems || [];
          serviceItems.value = items.map(item => ({
            ...item,
            currentPrice: Number(item.currentPrice) || 0,
            originalPrice: Number(item.originalPrice) || 0
          }));
          resolve();
        } else {
          reject(new Error(`请求失败，状态码：${res.statusCode}`));
        }
      },
      fail: (err) => {
        console.error('接口请求失败:', err);
        reject(err);
      }
    });
  });
};

// 修改后的获取评价方法
const fetchReviews = (storeId) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `http://localhost:10001/order/getOrderDetailsByStoreId?storeId=${storeId}`,
      success: (res) => {
        if (res.statusCode === 200) {
          // 提取serviceReview并处理图片
          reviews.value = res.data
            .filter(item => item?.serviceReview)  // 过滤无效数据
            .map(item => ({
              ...item.serviceReview,
              images: item.serviceReview.images 
                ? item.serviceReview.images.split(',') 
                : []
            }));
          console.log('处理后的评价数据:', reviews.value);
          resolve();
        } else {
          reject(new Error(`请求失败，状态码：${res.statusCode}`));
        }
      },
      fail: (err) => {
        console.error('评价接口请求失败:', err);
        reject(err);
      }
    });
  });
};
// 新增时间格式化方法
const formatDate = (isoString) => {
  try {
    return new Date(isoString).toISOString().split('T')[0].replace(/-/g, '.');
  } catch (e) {
    return '未知时间';
  }
};
// 错误处理
const handleError = (msg) => {
  uni.showModal({
    title: '提示',
    content: msg,
    showCancel: false,
    success: () => uni.navigateBack()
  });
};

// 导航到预约页面
const navigateToOrderConfirm = (serviceId) => {
  if (!serviceId) {
    uni.showToast({ title: '服务信息异常', icon: 'none' });
    return;
  }
  uni.navigateTo({
    url: `/pages/zhuanyexiche/WashCarInfo/OrderConfirm/OrderConfirm?serviceId=${serviceId}`
  });
};

// 电话相关功能保持不变
const openPhoneDialog = (phone) => {
  currentPhone.value = phone || '400-000-0000';
  phonePopup.value?.open();
};

const makePhoneCall = () => {
  uni.makePhoneCall({
    phoneNumber: currentPhone.value.toString(),
    success: () => phonePopup.value?.close()
  });
};

const closePhoneDialog = () => {
  phonePopup.value?.close();
};
</script>

<style>
/* 新增服务项目样式 */
.service-list {
  margin-top: 20rpx;
}

.service-item {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.service-info {
  flex: 2;
  margin-right: 20rpx;
}

.service-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 10rpx;
}

.service-desc {
  font-size: 26rpx;
  color: #888;
  line-height: 1.4;
}
/* 新增评价样式 */
.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.rating-stars {
  color: #ffc107;
  font-size: 32rpx;
}

.image-grid {
  display: flex;
  gap: 20rpx;
  margin-top: 24rpx;
  white-space: nowrap;
}

.comment-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.empty-comment {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}

.price-section {
  flex: 1;
  text-align: right;
  margin-right: 20rpx;
}

.current-price {
  font-size: 36rpx;
  color: #e53935;
  font-weight: bold;
  display: block;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  display: block;
  margin-top: 8rpx;
}

.service-order-btn {
  background: #07c160;
  color: #fff;
  font-size: 28rpx;
  padding: 12rpx 32rpx;
  border-radius: 40rpx;
  line-height: 1.5;
  white-space: nowrap;
}

.empty-tip {
  text-align: center;
  padding: 40rpx;
  color: #999;
}

/* 保留原有样式... */
.shop-header {
  position: relative;
  height: 420rpx;
}

.shop-banner {
  width: 100%;
  height: 100%;
  filter: brightness(0.9);
}

.shop-name {
  position: absolute;
  bottom: 40rpx;
  left: 32rpx;
  font-size: 44rpx;
  color: #fff;
  font-weight: 600;
  text-shadow: 2rpx 2rpx 6rpx rgba(0,0,0,0.3);
}

.info-card {
  background: #fff;
  padding: 32rpx;
  margin: 24rpx;
  border-radius: 20rpx;
  box-shadow: 0 6rpx 16rpx rgba(0,0,0,0.06);
}
/* 新增样式 */
.service-image {
  width: 100%;
  border-radius: 12rpx;
  margin: 20rpx 0;
  max-height: 400rpx;
}
/* 基础容器 */
.container {
  background-color: #f5f5f5;
  padding-bottom: 160rpx;
}

/* 店铺头部 */
.shop-header {
  position: relative;
  height: 420rpx;
}

.shop-banner {
  width: 100%;
  height: 100%;
  filter: brightness(0.9);
}

.shop-name {
  position: absolute;
  bottom: 40rpx;
  left: 32rpx;
  font-size: 44rpx;
  color: #fff;
  font-weight: 600;
  text-shadow: 2rpx 2rpx 6rpx rgba(0,0,0,0.3);
}

/* 信息卡片 */
.info-card {
  background: #fff;
  padding: 32rpx;
  margin: 24rpx;
  border-radius: 20rpx;
  box-shadow: 0 6rpx 16rpx rgba(0,0,0,0.06);
}

.info-line {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.rating {
  color: #ffc107;
  font-weight: 600;
  margin-right: 40rpx;
}

.sales {
  color: #666;
  margin-right: 40rpx;
}

.distance {
  color: #666;
}

.hours {
  display: block;
  color: #888;
  font-size: 28rpx;
  margin-bottom: 16rpx;
}

.address {
  color: #666;
  font-size: 28rpx;
  line-height: 1.6;
}

/* 服务项目 */
.service-card {
  background: #fff;
  margin: 24rpx;
  padding: 32rpx;
  border-radius: 20rpx;
}

.service-text {
  color: #444;
  font-size: 30rpx;
  line-height: 1.8;
  text-indent: 2em;
}

/* 用户评价 */
.comment-card {
  background: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
}

.comment-time {
  display: block;
  color: #999;
  font-size: 24rpx;
  margin-bottom: 16rpx;
}
.user-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.username {
  color: #333;
}

.comment-time {
  color: #999;
}

.comment-content {
  color: #666;
  line-height: 1.6;
  font-size: 28rpx;
}

/* 加载状态 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.loading-text {
  font-size: 32rpx;
  color: #666;
}

/* 底部操作栏 */
.footer-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
}

.contact-btn {
  flex: 1;
  background: #fff;
  color: #333;
  border: 1rpx solid #ddd;
  margin-right: 20rpx;
  transition: opacity 0.2s;
}

.contact-btn:active {
  opacity: 0.8;
}

.order-btn {
  flex: 2;
  background: #07c160;
  color: #fff;
  transition: opacity 0.2s;
}

.order-btn:active {
  opacity: 0.8;
}

/* 电话弹窗 */
.phone-dialog {
  background: #fff;
  width: 600rpx;
  border-radius: 24rpx;
  padding: 40rpx;
  text-align: center;
}

.phone-title {
  display: block;
  font-size: 32rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.phone-number {
  font-size: 48rpx;
  color: #333;
  font-weight: 600;
  margin: 40rpx 0;
  display: block;
}
.comment-item {
  border-bottom: 1rpx solid #eee;
  padding: 30rpx 0;
}
.dialog-buttons {
  display: flex;
  gap: 30rpx;
}

.call-btn, .cancel-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  transition: opacity 0.2s;
}

.call-btn {
  background: #07c160;
  color: #fff;
}

.call-btn:active {
  opacity: 0.9;
}

.cancel-btn {
  background: #f0f0f0;
  color: #666;
}

.cancel-btn:active {
  opacity: 0.9;
}

/* 弹窗遮罩 */
.uni-popup__wrapper {
  background-color: rgba(0, 0, 0, 0.5) !important;
}
/* 原有样式保持不变... */
/* 注意：需要保持原有的所有样式定义 */
</style>